package com.express.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: laixiangdong
 * @Date 2020/12/02
 */
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String path = config.getInitParameter("contentConfigLocation");
        InputStream resourceAsStream = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandlerMapping.load(resourceAsStream);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        HandlerMapping.MVCMapping mvcMapping = HandlerMapping.get(uri);
        if (mvcMapping == null) {
            resp.sendError(404, "映射地址不存在" + uri);
            return;
        }
        Method method = mvcMapping.getMethod();
        Object obj = mvcMapping.getObj();
        String result = null;
        try {
            result = (String) method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (mvcMapping.getType()) {
            case TEXT:
                resp.getWriter().write(result);
                break;
            case VIEW:
                resp.sendRedirect(result);
                break;
        }
    }
}
